"""
API视图模块
定义主机管理相关API端点
"""
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Host
import subprocess
import shlex
import platform

from .serializers import HostSerializer


class HostViewSet(viewsets.ModelViewSet):
    """
    主机管理视图集
    提供标准CRUD操作和自定义action
    """
    queryset = Host.objects.select_related('idc__city').all()
    serializer_class = HostSerializer

    @action(detail=True, methods=['get'], url_path='ping-check')
    def ping_check(self, request, pk=None):
        """
        自定义Action：执行主机网络可达性检查
        Parameters:
            pk (int): 主机ID
        Returns:
            JSON响应包含检测结果
        """
        host = self.get_object()
        param = '-n' if platform.system() == 'Windows' else '-c'

        # 安全构造命令参数
        command = [
            'ping',
            param,
            '3',
            shlex.quote(host.ip)  # 防止命令注入攻击
        ]

        try:
            subprocess.check_output(
                command,
                stderr=subprocess.STDOUT,
                timeout=10
            )
            return Response({'status': 'reachable', 'ip': host.ip})
        except subprocess.CalledProcessError:
            return Response(
                {'status': 'unreachable', 'ip': host.ip},
                status=500
            )
        except Exception as e:
            return Response(
                {'error': str(e), 'ip': host.ip},
                status=500
            )